<?php 

namespace IMT\ServicesBundle\Controller;

use IMT\Plugins\OrderBundle\Entity\Ordre;

use JMS\Serializer\SerializationContext;

use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\View\View;
use FOS\Rest\Util\Codes;

class OrderRestController extends Controller
{
	/**
	 * GET /order/{eventId}
	 *
	 * @param string $eventId
	 * @return Response
	 */
	public function getOrderAction($orderId)
	{			
		if(intval($orderId) == 0)
	    	throw new \InvalidArgumentException(400, 'L\'id est incorrect : '.$orderId);
	    
    	// Récupération de l'order
    	$repository = $this->getDoctrine()->getRepository('IMTPluginsOrderBundle:Ordre');
   		$order = $repository->findOneById($orderId);
   		
   		if (!$order)
   			throw new NotFoundHttpException('L\'ordre du jour ayant l\'id '.$orderId.' n\'existe pas');
   		   			   		
		$view = View::create()
			->setStatusCode(200)
			->setData(array(
				'id'=>$order->getId(),
				'position'=>$order->getPosition(),
				'state'=>$order->getState(),
				'content'=>$order->getContent(),
				'event'=>$order->getEvent()->getId(),
			));

		return $this->get('fos_rest.view_handler')->handle($view);
	}
	
	/**
	 * Creates a new Thread from the submitted data.
	 *
	 * @param Request $request The current request
	 *
	 * @return View
	 */
	public function postOrderAction(Request $request)
	{
		$idOrder = 0;
	
		$em = $this->getDoctrine()->getEntityManager();
		$viewHandler = $this->get('fos_rest.view_handler');
			
		if('POST' == $request->getMethod()){
			$idOrder = $request->request->get('order_id');
			
			$validator = $this->get('validator');
			
			$order = null;
						
			$user = $this->get('security.context')->getToken()->getUser();
	
			if($idOrder == 0){
				$order = new Ordre();
			} else {
				$order = $em->getRepository('IMTPluginsOrderBundle:Ordre')->find($idOrder);
					
				if(!$order)
					throw $this->createNotFoundException('L\'ordre du jour "'.$idOrder.'" n\'existe pas');
			}
			
			$order->setContent($request->request->get('order_content'));
			$order->setState($request->request->get('order_state'));
			$order->setPosition($request->request->get('order_position'));
			
			$idEvent = intval($request->request->get('order_event'));
			if($idEvent){
				$event = $em->getRepository('IMTEventBundle:Meeting')->find($idEvent);
			
				if($event){
					$order->setEvent($event);
				}
			}
									
			//return $viewHandler->handle($this->createErrorViewResponse($order));
			$errors = $validator->validate($order);
			
			if(count($errors) > 0){
				$return['errors'] = $errors;
			
				return $viewHandler->handle($this->createErrorViewResponse($return));
			} else {
				$em = $this->getDoctrine()->getEntityManager();
				$em->persist($order);
				$em->flush();
					
				$return['idOrder'] = $order->getId();
			
				return $viewHandler->handle($this->createSuccessViewResponse($return));
			}
		} else {
			throw new MethodNotAllowedException('POST');
		}
	
	}
	
	public function deleteOrderAction($id)
	{
		$em = $this->getDoctrine()->getEntityManager();
		$viewHandler = $this->get('fos_rest.view_handler');
			
		$entity = $em->getRepository('IMTPluginsOrderBundle:Ordre')->find($id);
		
		if (!$entity) {
			throw $this->createNotFoundException('L\'ordre du jour "'.$id.'" n\'existe pas');
		} 
		
		$em->remove($entity);
		$em->flush();
		
		return $viewHandler->handle($this->createSuccessViewResponse(array('idOrder' => $id)));
	}
	
	private function createSuccessViewResponse($return)
	{
		$view = View::create()
		->setStatusCode(200)
		->setData($return);
	
		return $view;
	}
	
	private function createErrorViewResponse($return)
	{
		$view = View::create()
		->setStatusCode(Codes::HTTP_BAD_REQUEST)
		->setData($return);
	
		return $view;
	}
}